#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "mystdio.h"
#include<sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>


static Myfile* BuyFile(int fd,int flag)
{
    Myfile* f=(Myfile*)malloc(sizeof(Myfile));
    if(f==NULL)return NULL;
    f->bufferlen=0;
    f->fileno=fd;
    f->flag=flag;
    f->fflush_method=LINE_FLUSH;
    memset(f->outbuffer,0,sizeof(f->outbuffer));
    return f;
}

Myfile* Myfopen(const char* path,const char* mode)
{
    int fd=-1;
    int flag=0;

    if(strcmp(mode,"w")==0)
    {
        flag=O_CREAT|O_WRONLY|O_TRUNC;
        fd=open(path,flag,0666);
    }
    else if(strcmp(mode,"a")==0)
    {
        flag=O_CREAT|O_WRONLY|O_APPEND;
        fd=open(path,flag,0666);
    }
    else if(strcmp(mode,"r")==0)
    {
        flag=O_RDONLY;
        fd=open(path,flag);
    }
    else 
    {
        //todo
    }

    if(fd<0)return NULL;
    
    return BuyFile(fd,flag);
}

void Myfclose(Myfile* file)
{
    if(file->fileno<0)return;
    Myfflush(file);
    close(file->fileno);
    free(file);

}

int Mywrite(Myfile* file,void* str,int len)
{
    memcpy(file->outbuffer+file->bufferlen,str,len);

    file->bufferlen+=len;

    if((file->fflush_method&LINE_FLUSH)&&file->outbuffer[file->bufferlen-1]=='\n')
    {
        Myfflush(file);
    }
    return 0;
}

void Myfflush(Myfile* file)
{
    if(file->bufferlen<=0)return;
    write(file->fileno,file->outbuffer,file->bufferlen);
    fsync(file->fileno);
    file->bufferlen=0;
}


